//
// Created by 张亦乐 on 2018/9/18.
//
#include "MsgCenter.hpp"
#include "base/Timestamp.hpp"
#include "hybrid/google/Dispatcher.hpp"

using namespace std;
using namespace ProtoMsg;
const int HEADSIZE = 4;
MsgCenter::MsgCenter():
    _worker("MsgCenter"),
    _quit(false)
{

}

void MsgCenter::loop()
{
    while(!_quit)
    {
        auto oneMsg = _msgs.front();
	   //  uint64_t nowms = Timestamp::Nowms();
		// printf("MsgCenter::loop queue spent time ms  = %ld\n",nowms - oneMsg.ts);
        ProtobufDispatcher::GetInstance()->onProtobufMessage(oneMsg.conn,oneMsg.packet);
    }
}

bool MsgCenter::Parse(Buffer& buff,TcpConnectorPtr& tcpConn)
{
    if(buff.ReadableBytes() < HEADSIZE)
    {
        return true;
    }

    auto head = buff.Peek(HEADSIZE);
    uint32_t payloadSize;
    memcpy(&payloadSize,&head[0],4);

    uint32_t packetSize = HEADSIZE + payloadSize;
    if(buff.ReadableBytes() >= packetSize)
    {
        PacketPtr pack(new Packet());
        buff.Read(HEADSIZE);
	    if(pack->ParseFromString(buff.Read(payloadSize)))
        {
			// uint64_t diff = Timestamp::Nowms() - pack->timestamp();
			// printf("MsgCenter::Parse() time interval %ld \n",diff);
			// uint64_t nowms = Timestamp::Nowms();
            _msgs.push(MsgTask{tcpConn,pack/*,nowms*/});
            return true;
        }
    }
    return false;
}

void MsgCenter::Start()
{
    _worker.SetWorkCallback(std::bind(&MsgCenter::loop,this));
    _worker.StartWork();
}

